package com.hutao.medical.controller.interceptor;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.hutao.medical.common.util.CookieUtils;
import com.hutao.medical.common.util.HttpClientUtil;
import com.hutao.medical.common.util.PropsUtil;
import com.hutao.medical.pojo.user.User;

public class MyInterceptor1 implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		  //System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		//System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		// TODO Auto-generated method stub
		if(response.getStatus() == HttpStatus.NOT_FOUND.value()){
			return true;
		}
		User users = (User) request.getSession().getAttribute("user");
		Cookie[] cookies = request.getCookies();
			
			if (null != cookies) {
				for (Cookie c : cookies) {
					String cookieName = c.getName();
					String cookieValue = c.getValue();
					if (cookieName.contains("TT_TOKEN") && StringUtils.isNotBlank(cookieValue) && null != users) {
						//String loginName = cookieValue;
						Subject subject = SecurityUtils.getSubject();
						Session session = subject.getSession();
						CookieUtils.setCookie(request, response, "TT_TOKEN", cookieValue, 15000);
						String name = CookieUtils.getCookieValue(request, "userName");
						String officeCode = CookieUtils.getCookieValue(request, "officeCode");
						String officeName = CookieUtils.getCookieValue(request, "officeName");
						CookieUtils.setCookie(request, response, "officeCode", officeCode, 15000);
						CookieUtils.setCookie(request, response, "officeName", officeName, 15000);
						CookieUtils.setCookie(request, response, "userName", name, 15000);
						String medicalMainstayId = CookieUtils.getCookieValue(request, "medicalMainstayId");
						CookieUtils.setCookie(request, response, "medicalMainstayId", medicalMainstayId, 15000);
						String userId = CookieUtils.getCookieValue(request, "userId");
						CookieUtils.setCookie(request, response, "userId", userId, 15000);
						session.setAttribute("loginName", name);
						User user = new User();
						user.setName(name);
						user.setMedicalMainstayId(medicalMainstayId);
						user.setId(userId);
						session.setAttribute("user", user);
						return true;
						//cookie的值和usres的是否一致
//						if(loginName.equals(users.getLoginName()) && password.equals(users.getPassword())) {
//							c.setMaxAge(1800);
//							return true;
//						}
					}
				}
			} 
		
		//获取contextPath
		String contextPath = request.getContextPath();
		int index = contextPath.lastIndexOf("/");
		contextPath = contextPath.substring(index+1);
		Properties pro = PropsUtil.loadProps("config.properties");
		String login_url_new1 = pro.getProperty("phr.config.sso.loginByUserName");
		if (null != cookies) {
			for (Cookie c : cookies) {
				String cookieName = c.getName();
				String cookieValue = c.getValue();
				if (cookieName.contains("TT_TOKEN") && StringUtils.isNotBlank(cookieValue)) {
					String loginName = cookieValue;
					
					//远程调用sso系统
					Map<String, String> params = new HashMap<>();
					params.put("username", loginName);
					params.put("contextPath", contextPath);
					// 远程调用sso登录系统
					String userJson = HttpClientUtil.doPost(login_url_new1, params);

					JSONObject userMap = JSONObject.parseObject(userJson);

					if ((boolean) userMap.get("isSuccess")) {
						Subject subject = SecurityUtils.getSubject();
						Session session = subject.getSession();
						session.setAttribute("contextPath", contextPath);
						UsernamePasswordToken token = new UsernamePasswordToken(loginName, (String)userMap.get("password"));
						subject.login(token);
						String name = userMap.get("name")!=null&&userMap.get("name")!=""?(String)userMap.get("name"):"";
						String officeCode = userMap.get("officeCode")!=null&&userMap.get("officeCode")!=""?(String)userMap.get("officeCode"):"";
						String officeName = userMap.get("officeName")!=null&&userMap.get("officeName")!=""?(String)userMap.get("officeName"):"";
						User user = new User();
						user.setId((String)userMap.get("id"));
						user.setLoginName(loginName);
						user.setPassword((String)userMap.get("password"));
						user.setContextPath(contextPath);
						user.setName(name);
						user.setMedicalMainstayId((String)userMap.get("medicalMainstayId"));
						user.setName(name);
						session.setAttribute("user", user);
						session.setAttribute("loginName", name);
						CookieUtils.setCookie(request, response, "TT_TOKEN", loginName, 15000);
						CookieUtils.setCookie(request, response, "userName", name, 15000);
						CookieUtils.setCookie(request, response, "officeCode", officeCode, 15000);
						CookieUtils.setCookie(request, response, "officeName", officeName, 15000);
						CookieUtils.setCookie(request, response, "medicalMainstayId", (String)userMap.get("medicalMainstayId"), 15000);
						CookieUtils.setCookie(request, response, "userId", (String)userMap.get("id"), 15000);
						return true;
					}
					
					response.sendRedirect(request.getContextPath() + "/user/toLogin");
					return false;
				}
			}
		} 
		response.sendRedirect(request.getContextPath() + "/user/toLogin");
		return false;
	}
}
